<?php
//用户管理
namespace app\adminbackstage\controller;
use app\BaseController;
use app\adminbackstage\model\User;
use app\adminbackstage\model\UserChange;
use app\common\model\UserAmountRewardDetailed;
use app\common\model\UserAmount;
use app\adminbackstage\model\Order;

use app\adminbackstage\model\Product;
//use think\facade\Session;
use think\facade\Request;
use think\facade\Db;

/**
 * Description of UserManagementController
 *
 * @author asus80
 */
class UserManagementController  extends BaseController {
   
    public function userList(){
        $page = Request::param('page');
        $num = Request::param('num');
        $type = Request::param('type');//类型  1后台管理员 2后台普通管理员 21 驿站 22团长 23 用户 24门店 25虚拟凑数用户 26供应商
        

        $enable = Request::param('enable');
        $start = Request::param('starttime');
        $end = Request::param('endtime');
        $phone = Request::param('phone');
        $username = Request::param('username');
        $stid = Request::param('stid');
        //$store_name = Request::param('s_name');

        $a_uid = Request::param('a_uid');//管理员ID
        if(!empty($a_uid)){
            $user = new User();
            $where_u[] = ["u.uid",'=',$a_uid];
            $find = $user->find($where_u);
            if(empty($find)){
                return json(['code' => -200, 'msg' => lang('无菜单权限'), 'data' => '', 'count' => '']);
            }
            else{
                $find = $find->toArray();
                if($find['enable']!=1){
                    return json(['code' => -200, 'msg' => lang('无菜单权限'), 'data' => '', 'count' => '']);
                }
            }
        }

        $where = [];
        if(!empty($start)){
            $time_start = strtotime($start);
            $where[] = ['u.addtime','>=',$time_start];
        }
        
        if(!empty($end)){
            $time_end = strtotime($end)+(24*3600-1);
            $where[] = ['u.addtime','<',$time_end];
        }
        

        if(!empty($enable)){
            if($enable == -1){
                $enable = 0;
            }
            $where[] = ['u.enable','=',$enable];
        }
        
        if(!empty($username)){
            $where[] = ['u.username','=',$username];
        }
        
        if(!empty($username)){
            $where[] = ['u.stid','=',$stid];
        }

        if(!empty($phone)){
            $where[] = ['u.phone','=',$phone];
        }
        
        if(!empty($type)){
            $where[] = ['u.type','=',$type];
        }
        
        /*if(!empty($store_name)){
            $where[] = ['s.store_name','like','"'.$store_name.'"'];
        }*/
        

            
        $user = new User();
        $listinfo = $user->listUser($page,$num,$where)->toArray();
        
        $count = $user->countUser($where); 
     

        foreach ($listinfo as $key => $value) {

            
            
            if($value['enable']==0){
                $listinfo[$key]['user_enable'] = '未启用';
            }
            elseif ($value['enable']==1) {
                $listinfo[$key]['user_enable'] = '启用';
            }

            if(!empty($value['addtime'])){
                $listinfo[$key]['addtime'] = date( "Y-m-d H:i:s",$value['addtime']); 
            }
            if (empty($value["superor_phone"])){
                $listinfo[$key]['superor_phone'] = $value["superor"];
            }
//            if(!empty($value['lasttime'])){
//                $listinfo[$key]['lasttime'] = date( "Y-m-d H:i:s",$value['lasttime']); 
//            }
            
        }

        return json(['code' => 1, 'msg' => lang(''), 'data' => $listinfo, 'count' => $count]);

    }
    
    //修改管理员用户名,密码
    public function userPwe() {
        $a_uid = Request::param('a_uid');
        $uid = Request::param('uid');
        $pw = Request::param('pw');
//        $old_pw = Request::param('old_pw');
        $username = Request::param('user');
        $user = new User();
        if(!empty($uid)){
            $where[] = ["u.uid","=",$uid];
        }
        
        if(!empty($username)){
            $where[] = ["u.username","=",$username];
        }
        
        $find = $user->find($where);
        if(!empty($find)){
            $find = $find->toArray();
            $encryption = $find['encryption'];
            $password = $find['password'];
        }
        else{
            return json(['code' => 0, 'msg' => lang('用户不存在'), 'data' => '', 'count' => '']);
        }

        
        $pw = $this->encPassword($pw,$encryption);//密码
        if(!empty($username)){
            $update = ['username' => $username];
            $user->userUpdate($uid,$update);
        }
        if(!empty($pw)){
            $update = ['password' => $pw];
            $user->userUpdate($uid,$update);
        }

        return json(['code' => 1, 'msg' => lang(''), 'data' => '', 'count' => '']);
    }
    
    //添加管理员
    public function add_user(){
        $a_uid = Request::param('a_uid');
        if($a_uid != 1 ){
            //return json(['code' => 0, 'msg' => lang('该账号无操作权限'), 'data' =>'', 'count' => '']);
        }
        $username = Request::param('user');
        $pw = Request::param('pw');
        $time = time();
        $user = new User();
        
        $where[] = ["u.username","=",$username];
        $find = $user->find($where);
        if(!empty($find)){
            return json(['code' => 0, 'msg' => lang('用户已存在'), 'data' => '', 'count' => '']);
        }

        $encryption = self::createNonceStr($length = 4);
        $password = self::encPassword($pw,$encryption);//密码
        $data = [
                'username' => $username,
                'password' => $password,
                'type' => 2,
                'encryption' => $encryption,
                'addtime' => $time,
            ];
        $user->add_user($data);
        return json(['code' => 1, 'msg' => lang(''), 'data' => '', 'count' => '']);
    }
    
    //添加驿站用户
    public function addTuser(){
        $a_uid = Request::param('a_uid');
        if($a_uid != 1 ){
            //return json(['code' => 0, 'msg' => lang('该账号无操作权限'), 'data' =>'', 'count' => '']);
        }
        $username = Request::param('user');
        $pw = Request::param('pw');
//        $type = Request::param('type');
        $phone = Request::param('phone');
        
        

        $time = time();
        $user = new User();
        
        $where[] = ["u.username","=",$username];
        $find = $user->find($where);
        if(!empty($find)){
            return json(['code' => 0, 'msg' => lang('用户已存在'), 'data' => '', 'count' => '']);
        }
        
        $where_[] = ["u.phone","=",$phone];
        $find_ = $user->find($where_);
        if(!empty($find_)){
            return json(['code' => 0, 'msg' => lang('手机号码已存在'), 'data' => '', 'count' => '']);
        }

        $encryption = self::createNonceStr($length = 4);
        $password = self::encPassword($pw,$encryption);//密码
        $data = [
                'username' => $username,
                'password' => $password,
                'phone' => $phone,
                'type' => 21,
                'encryption' => $encryption,
                'extension' => self::extensionCreat(),
                'addtime' => $time,
            ];
        $channelUserId = $user->add_user($data);
        UserAmount::userAmountAdd($channelUserId);//建立资金表
        return json(['code' => 1, 'msg' => lang(''), 'data' => '', 'count' => '']);
    }
    
    //添加门店用户
    public function addSuser(){
        $a_uid = Request::param('a_uid');
        if($a_uid != 1 ){
            //return json(['code' => 0, 'msg' => lang('该账号无操作权限'), 'data' =>'', 'count' => '']);
        }
        $username = Request::param('user');
        $pw = Request::param('pw');
        $stid = Request::param('stid');
        $phone = Request::param('phone');
        $store_name = Request::param('store_name');
        

        $time = time();
        $user = new User();
        
        $where[] = ["u.username","=",$username];
        $find = $user->find($where);
        if(!empty($find)){
            return json(['code' => 0, 'msg' => lang('用户已存在'), 'data' => '', 'count' => '']);
        }
        
        $where_[] = ["u.phone","=",$phone];
        $find_ = $user->find($where_);
        if(!empty($find_)){
            return json(['code' => 0, 'msg' => lang('手机号码已存在'), 'data' => '', 'count' => '']);
        }
        
        $where_s[] = ["u.stid","=",$stid];
        $where_s[] = ["u.type","=",24];
 
        $find_s = $user->find($where_s);
        if(!empty($find_s)){
            return json(['code' => 0, 'msg' => lang('该门店已存在门店用户'), 'data' => '', 'count' => '']);
        }

        $encryption = self::createNonceStr($length = 4);
        $password = self::encPassword($pw,$encryption);//密码
        $data = [
                'username' => $username,
                'password' => $password,
                'phone' => $phone,
                'stid' => $stid,
                'store_name' => $store_name,
                'type' => 24,
                'encryption' => $encryption,
                'extension' => self::extensionCreat(),
                'commission_rate' => 15,
                'addtime' => $time,
            ];
        $channelUserId = $user->add_user($data);
        
        UserAmount::userAmountAdd($channelUserId);//建立资金表
        return json(['code' => 1, 'msg' => lang(''), 'data' => '', 'count' => '']);
    }
    
    
    //添加供应商用户
    public function addSupplieruser(){
        $a_uid = Request::param('a_uid');
        if($a_uid != 1 ){
            //return json(['code' => 0, 'msg' => lang('该账号无操作权限'), 'data' =>'', 'count' => '']);
        }
        $username = Request::param('user');
        $pw = Request::param('pw');
        //$stid = Request::param('stid');
        $phone = Request::param('phone');
        //$store_name = Request::param('store_name');
        

        $time = time();
        $user = new User();
        
        $where[] = ["u.username","=",$username];
        $find = $user->find($where);
        if(!empty($find)){
            return json(['code' => 0, 'msg' => lang('用户已存在'), 'data' => '', 'count' => '']);
        }
        
        $where_[] = ["u.phone","=",$phone];
        $find_ = $user->find($where_);
        if(!empty($find_)){
            return json(['code' => 0, 'msg' => lang('手机号码已存在'), 'data' => '', 'count' => '']);
        }
        
//        $where_s[] = ["u.stid","=",$stid];
//        $where_s[] = ["u.type","=",24];
// 
//        $find_s = $user->find($where_s);
//        if(!empty($find_s)){
//            return json(['code' => 0, 'msg' => lang('该门店已存在门店用户'), 'data' => '', 'count' => '']);
//        }

        $encryption = self::createNonceStr($length = 4);
        $password = self::encPassword($pw,$encryption);//密码
        $data = [
                'username' => $username,
                'password' => $password,
                'phone' => $phone,
                //'stid' => $stid,
                //'store_name' => $store_name,
                'type' => 26,
                'encryption' => $encryption,
                'extension' => self::extensionCreat(),
                'commission_rate' => 15,
                'addtime' => $time,
            ];
        $channelUserId = $user->add_user($data);
        
        UserAmount::userAmountAdd($channelUserId);//建立资金表
        return json(['code' => 1, 'msg' => lang(''), 'data' => '', 'count' => '']);
    }
    
    //人员修改
    public function userEdit(){
        $user = new User();
        $a_uid = Request::param('a_uid');
        $commission_rate = Request::param('commission_rate');//佣金比例
        $username = Request::param('user');
        $nickname = Request::param('nickname');
        if($a_uid != 1 ){
            //return json(['code' => 0, 'msg' => lang('该账号无操作权限'), 'data' =>'', 'count' => '']);
        }
        $uid = Request::param('uid');
        $enable = Request::param('enable');
        
        $update = [];
        $where = [];
        $where_z = [];
        $update_s = [];//用户保存的团长名
        if(!empty($enable)){
            if($enable == -1){
                $enable = 0;
            }
            $update['enable'] = $enable;

        }
        
        if(!empty($commission_rate)){
            $update['commission_rate'] = $commission_rate;
        }
        //类型  1后台管理员 2后台普通管理员 21 驿站 22团长 23 用户 24门店 25虚拟凑数用户 26供应商
        if(!empty($username)){
            $where[] = ['u.username','=',$username];
            $find = $user->find($where);
            if(!empty($find)){
                return json(['code' => 0, 'msg' => lang('用户名驿存在'), 'data' =>'', 'count' => '']);
            }
            $update['username'] = $username;
            $where_z[] = ['u.uid','=',$uid];
            $find_z = $user->find($where_z);
            if(!empty($find_z)){
                $find_z = $find_z->toArray();
                if($find_z['type']==22){
                    $update_s['superor'] = $username;
                }
                elseif ($find_z['type']==21) {
                    $update_s['post_sta'] = $username;
                }
                elseif ($find_z['type']==26) {
                    $update_s['supplier'] = $username;
                }
                
            }
        }
        
        if(!empty($nickname)){
            $update['nickname'] = $nickname;
        }
        Db::startTrans();//开启事务
        if(!empty($update)){
            $user->userEdit($uid,$update);
            
            if(!empty($update_s)){
                $where_s = [];
                
                if($find_z['type']==22){
                    $where_s[] = ['superor_id','=',$uid];
                    $user->userUpdateAll($where_s,$update_s);
                }
                elseif ($find_z['type']==21) {
                    $where_s[] = ['post_sta_id','=',$uid];
                    $user->userUpdateAll($where_s,$update_s);
                }
                elseif($find_z['type']==26) {
                    $where_s[] = ['supplier_id','=',$uid];
                    Product::productUpdateAll($where_s,$update_s);
                }
                
                
            }
        }
        Db::commit();//事务提交

        return json(['code' => 1, 'msg' => lang(''), 'data' =>'', 'count' => '']);
    }
    
    //用户上级变更
    public function userSuperiorChange(){
        $user = new User();
        $a_uid = Request::param('a_uid');
        $uid = Request::param('uid');
        $enable = Request::param('enable',1);
        $where_o[] = ["u.uid","=",$uid];
        $find_o = $user->find($where_o);
        if(!empty($find_o)){
            $find_o = $find_o->toArray();
        }
        else{
            return json(['code' => 0, 'msg' => lang('用户不存在'), 'data' => '', 'count' => '']);
        }
        
        $phone = Request::param('phone');//新上级
        $where[] = ["u.phone","=",$phone];
        $find = $user->find($where);
        
        if(empty($find)){
            $find = '';
            $where = [];
            $where[] = ["u.username","=",$phone];
            $find = $user->find($where);
        }
        
        if(!empty($find)){
            $find = $find->toArray();
//            $encryption = $find['encryption'];
//            $password = $find['password'];
            //类型 1后台管理员 2后台普通管理员 21 驿站 22团长 23 用户
            if($find_o['type']==22){
                if($find['type'] != 21){
                    return json(['code' => 0, 'msg' => lang('该用户为团长，只能归属于驿站名下'), 'data' => '', 'count' => '']);
                }
                
                $update['post_sta'] = $find['username'];
                $update['post_sta_phone'] = $find['phone'];
                $update['post_sta_id'] = $find['uid'];
                //id,,uid,,a_uid,管理员ID,type,变更类别 1上级变更  2身份变更,sup_old,原上级ID,sup_new,现上级ID,ide_old,原身份,ide_new,现身份,reserved_1,,enable,,addtime,
                $time = time();
                $enable = 1;
                $data = [
                    'uid' => $uid,
                    'a_uid' => $a_uid,
                    'addtime' => $time,
                    'type' => 1,
                    'sup_old' => $find_o['post_sta_id'],
                    'sup_new' => $find['uid'],
                    'ide_old' => $find_o['type'],
                    'ide_new' => $find_o['type'],
                    'enable' => $enable,
                    'addtime' => $time,
                ];
            }
            elseif($find_o['type']==23){
                if($find['type'] != 22){
                    return json(['code' => 0, 'msg' => lang('该用户只能归属于团长名下'), 'data' => '', 'count' => '']);
                }
                $update['superor_sta'] = $find['username'];
                $update['superor_phone'] = $find['phone'];
                $update['superor_id'] = $find['uid'];
                $update['post_sta'] = $find['post_sta'];
                $update['post_sta_phone'] = $find['post_sta_phone'];
                $update['post_sta_id'] = $find['post_sta_id'];
                $time = time();
                $data = [
                    'uid' => $uid,
                    'a_uid' => $a_uid,
                    'addtime' => $time,
                    'type' => 1,
                    'sup_old' => $find_o['superor_id'],
                    'sup_new' => $find['uid'],
                    'ide_old' => $find_o['type'],
                    'ide_new' => $find_o['type'],
                    'enable' => $enable,
                    'addtime' => $time,
                ];

            }
            
        }
        else{
            return json(['code' => 0, 'msg' => lang('用户不存在'), 'data' => '', 'count' => '']);
        }
        
        UserChange::userChangeAdd($data);
        $user->userEdit($uid,$update);
        return json(['code' => 1, 'msg' => lang(''), 'data' => '', 'count' => '']);
    }
    
    //用户
    public function userInvite(){
        $user = new User();
        $a_uid = Request::param('a_uid');
        $uid = Request::param('uid');
        
        $page = Request::param('page');
        $num = Request::param('num');

        $where_u[] = ["u.uid","=",$uid];
        $find = $user->find($where_u);
        $where = [];
        
        if(empty($find)){
            return json(['code' => 0, 'msg' => lang('用户不存在'), 'data' => '', 'count' => '']);
        }
        else{
            $find = $find->toArray();
            if($find['type']==21){
//                $where[] = ['u.type','=',22];
                $where[] = ['u.post_sta_id','=',$uid];
            }
            elseif($find['type']==22){
//                $where[] = ['u.type','=',23];
                $where[] = ['u.superor_id','=',$uid];
            }
            else{
                return json(['code' => 0, 'msg' => lang('用户类型错误'), 'data' => '', 'count' => '']);
            }
        }
        
        
        
        $listinfo = $user->listUser($page,$num,$where)->toArray();
        foreach ($listinfo as $key => $value) {
            if($value['enable']==0){
                $listinfo[$key]['user_enable'] = '未启用';
            }
            elseif ($value['enable']==1) {
                $listinfo[$key]['user_enable'] = '启用';
            }

            if(!empty($value['addtime'])){
                $listinfo[$key]['addtime'] = date( "Y-m-d H:i:s",$value['addtime']); 
            }
        }
        $count = $user->countUser($where); 
        return json(['code' => 1, 'msg' => lang(''), 'data' => $listinfo, 'count' => $count]);
    }

    
    //用户身份变更
    public function userIdentityChange(){
        $user = new User();
        $a_uid = Request::param('a_uid');
        $uid = Request::param('id');
        $enable= Request::param('enable',1);
        $where_o[] = ["u.uid","=",$uid];
        $find_o = $user->find($where_o);
        if(!empty($find_o)){
            $find_o = $find_o->toArray();
        }
        else{
            return json(['code' => 0, 'msg' => lang('用户不存在'), 'data' => '', 'count' => '']);
        }
        
        $phone = Request::param('phone');//上级驿站
        $where[] = ["u.phone","=",$phone];
        $find = $user->find($where);
        if(empty($find)){
            $find = '';
            $where = [];
            $where[] = ["u.username","=",$phone];
            $find = $user->find($where);
        }
        
        if(!empty($find)){
            $find = $find->toArray();
//            $encryption = $find['encryption'];
//            $password = $find['password'];
            //类型 1后台管理员 2后台普通管理员 21 驿站 22团长 23 用户
            if($find_o['type']==23){
                if($find['type'] != 21){
                    return json(['code' => 0, 'msg' => lang('该用户不能变更为团长'), 'data' => '', 'count' => '']);
                }
                $update['superor_sta'] = '';
                $update['superor_phone'] = '';
                $update['superor_id'] = '';
                $update['post_sta'] = $find['username'];
                $update['post_sta_phone'] = $find['phone'];
                $update['post_sta_id'] = $find['uid'];
                $update['type'] = 22;
                $update['commission_rate'] = 85;
                $time = time();
                $data = [
                    'uid' => $uid,
                    'a_uid' => $a_uid,
                    'addtime' => $time,
                    'type' => 2,
                    'sup_old' => $find_o['superor_id'],
                    'sup_new' => $find['uid'],
                    'ide_old' => $find_o['type'],
                    'ide_new' => 22,
                    'enable' => $enable,
                    'addtime' => $time,
                ];

            }
            
        }
        else{
            return json(['code' => 0, 'msg' => lang('用户不存在'), 'data' => '', 'count' => '']);
        }
        
        UserChange::userChangeAdd($data);
        $user->userEdit($uid,$update);
        return json(['code' => 1, 'msg' => lang(''), 'data' => '', 'count' => '']);
    }
    
    //用户详情
    public function userInfo(){
        $uid = Request::param('uid');
        $user = new User();
        $where[] = ['u.uid','=',$uid];
        $return = $user->find($where)->toArray();//用户详情 会员等级
        $return['addtime'] = date( "Y-m-d H:i:s",$return['addtime']); 
        
        if(isset($return['lasttime'])){
            $return['lasttime'] = date( "Y-m-d H:i:s",$return['lasttime']); 
        }
        $ua_where[] = ["uid","=",$uid];
        $ua_where[] = ["state","=",1];
        $ua_where[] = ["type","in","1,2,3"];
        $userAmountCount = UserAmountRewardDetailed::orderRewardSum($ua_where,"amount_money");
        
        $return['userAmountCount']=$userAmountCount;
        
        $userAmount = UserAmount::userAmountInfo(['uid'=>$uid]);//获取用户可用余额
        
        $return['balance']= $userAmount['balance'];
        $return['freezing_amount']= $userAmount['freezing_amount'];
        $return['orderCount'] = 0;
        if($return['type']==23){
            $where_o = [];
            $where_o[] = ['o.uid','=',$uid];
            $where_o[] = ['o.state','<>',1];
            $return['orderCount'] = Order::orderCount($where_o);
        }

        $where_u = [];
        $return['postCount'] = 0;
        $return['superorCount'] = 0;
        if($return['type']==21){
            $where_u[] = ['u.type','=',22];
            $where_u[] = ['u.post_sta_id','=',$uid];
            $return['postCount'] = $user->countUser($where_u); 
        }
        elseif($return['type']==22){
            $where_u[] = ['u.type','=',23];
            $where_u[] = ['u.superor_id','=',$uid];
            $return['superorCount'] = $user->countUser($where_u); 
        }

        return json(['code' => 1, 'msg' => lang(''), 'data' => $return, 'count' => '']);

    }



    //生成邀请码
    public static function extensionCreat(){
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0,25)] .strtoupper(dechex(date('m'))) .date('d').substr(time(),-5) .substr(microtime(),2,5) .sprintf('%02d',rand(0,99));
        for( $a = md5( $rand, true ), $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV', $d = '', $f = 0; $f < 8; $g = ord( $a[ $f ] ), $d .= $s[ ( $g ^ ord( $a[ $f + 8 ] ) ) - $g & 0x1F ], $f++ );
        $superorUser = \app\common\model\User::userInfo("extension = binary '$d'"); //邀请码采用二进制 区分大小写
        if($superorUser){
            return self::extensionCreat();
        }
        return $d;
    }

}
